import * as THREE from "three";
import gsap from "gsap";
import * as dat from "dat.gui";

// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// 1.创建场景
const scene = new THREE.Scene();
// 2. 创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 设置相机位置
camera.position.set(0, 0, 10);
// 添加相机到场景中
scene.add(camera);

// 导入纹理
const textureLoader = new THREE.TextureLoader();
const floorColor = textureLoader.load(require("../assets/img/door/color.jpg"));
// 添加黑则隐白则显的纹理用于透明化非主体部分
const doorAplhaColor = textureLoader.load(require("../assets/img/door/alpha.jpg"));

// 3. 创建几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 材质
const material = new THREE.MeshBasicMaterial({
  // color: 0x00ff00,
  map: floorColor,
  alphaMap: doorAplhaColor,
  transparent: true,
});
// 关联几何体和材质
const cube = new THREE.Mesh(geometry, material);

// 添加几何体到场景
scene.add(cube);

// 应用图形界面更改变量
const gui = new dat.GUI();
gui
  .add(cube.position, "x")
  .min(0)
  .max(5)
  .step(0.05)
  .name("移动x坐标")
  .onChange((value) => {
    console.log("值被修改了：", value);
  });

// 修改物体的颜色
const params = {
  color: "#fff",
  fn: () => {
    gsap.to(cube.position, {
      x: 5,
      ease: "power1.out",
      duration: 5,
      repeat: -1,
      yoyo: true,
    });
  },
};
gui.addColor(params, "color").onChange((value) => {
  cube.material.color.set(value);
});

// 设置是否显示
gui.add(cube, "visible").name("是否显示");

// 设置按钮点击触发某个事件
var folder = gui.addFolder("设置立方体");
folder.add(cube.material, "wireframe");
folder.add(params, "fn").name("立方体运动");

// 4. 初始化渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);


window.addEventListener("dblclick", () => {
  const fullScreenElement = document.fullscreenElement;
  // 双击屏幕进入全屏
  if (!fullScreenElement) renderer.domElement.requestFullscreen();
  else document.exitFullscreen();
});

function animate() {
  controls.update();
  renderer.render(scene, camera);
  // 渲染下一帧的时候就调用animate
  requestAnimationFrame(animate);
}
animate();

// 监听画面变化
window.addEventListener("resize", () => {
  const iwidth = window.innerWidth;
  const iheigt = window.innerHeight;
  //更新摄像头
  camera.aspect = iwidth / iheigt;
  // 更新摄像机投影矩阵
  camera.updateProjectionMatrix();
  // 更新渲染器
  renderer.setSize(iwidth, iheigt);
  // 设置渲染器像素比
  renderer.setPixelRatio(window.devicePixelRatio);
});
